//
//  HLEAppDelegate.m
//  HLELowcostPeripherial
//
//  Created by ldb on 05/04/2021.
//  Copyright (c) 2021 ldb. All rights reserved.
//

#import "HLEAppDelegate.h"
#import <DoraemonKit/DoraemonManager.h>

@implementation HLEAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [[DoraemonManager shareInstance] installWithPid:@"aead5d6a3a41cdf7082e09462a005593"];

    [HLELowcostScheduler initLowcostDeviceSDK:25 normalTimeout:12];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}



#if 0
- (void)connectPeripheralBySerialNum:(NSString *)serialNum result:(void (^)(void))result
{
    NSLog(@"=========执行了");
    [self.dict setValue:result forKey:serialNum];
    @weakify(self);
    HLELowcostBleInforModel *bleInforModel = [[HLELowcostBleInforModel alloc] init];
    bleInforModel.serialNum = serialNum;
    self.baby.scanForPeripherals().begin();

    //设置查找设备的过滤器
    [self.baby setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
        NSString *str = [HLELowcostScheduler hle_getSerialNumWithAdvertisementData:advertisementData];
        return [str isEqualToString:serialNum];
    }];
    
    //设置扫描到设备的委托
    [self.baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        NSLog(@"搜索到了设备:%@",peripheral.name);
        bleInforModel.deviceName = advertisementData[@"kCBAdvDataLocalName"];
        @strongify(self);
        [self.baby cancelScan];
        self.baby.having(peripheral).and.connectToPeripherals().discoverServices().discoverCharacteristics().begin();
    }];

    [self.baby setBlockOnDiscoverCharacteristics:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
        @strongify(self);
        NSLog(@"发现特征");
        for (CBCharacteristic *cha in service.characteristics) {
            if([[cha.UUID.UUIDString uppercaseString] isEqualToString:@"FFF3"]){
                bleInforModel.writeCharacteristics = cha;
            }else if([[cha.UUID.UUIDString uppercaseString] isEqualToString:@"FFF4"]){
                bleInforModel.notifyCharacteristics = cha;
                [peripheral setNotifyValue:YES forCharacteristic:cha];
                [self.baby notify:peripheral
              characteristic:cha
                       block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
                    NSLog(@"uuidstring %@,new value %@",characteristics.UUID.UUIDString,characteristics.value);
                }];
            }
        }
    }];
    
    [self.baby setBlockOnConnected:^(CBCentralManager *central, CBPeripheral *peripheral) {
        @strongify(self);
        bleInforModel.peripheral = peripheral;
        [self addPeripheral:bleInforModel];
        NSLog(@"连接成功=========%@",bleInforModel.serialNum);
        void (^resultBlock)(void) = [self.dict valueForKey:serialNum];
        if (resultBlock) resultBlock();
        [self.dict removeObjectForKey:serialNum];
    }];
    
    [self.baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        @strongify(self);
        bleInforModel.peripheral = peripheral;
        [self deletePeripheral:bleInforModel];
        NSLog(@"连接失败=========%@",bleInforModel.serialNum);
        void (^resultBlock)(void) = [self.dict valueForKey:serialNum];
        if (resultBlock) resultBlock();
        [self.dict removeObjectForKey:serialNum];
    }];
    
    [self.baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        NSLog(@"断开连接=========%@",peripheral);
        @strongify(self);
        HLELowcostBleInforModel *bleInforModel = [[HLELowcostBleInforModel alloc] init];
        bleInforModel.peripheral = peripheral;
        [self deletePeripheral:bleInforModel];
    }];
}

- (void)sendMsgBySerialNum:(NSString *)serialNum data:(NSData *)data
{
    @weakify(self);
    HLELowcostBleInforModel *discovermodel;
    HLELowcostBleInforModel *model = [[self.connectedPeripherals qmui_filterWithBlock:^BOOL(HLELowcostBleInforModel *item) {
        return [item.serialNum isEqualToString:serialNum];
    }] objectOrNilAtIndex:0];
    if (model && model.peripheral.state == CBPeripheralStateConnected ) {
        [HLELowcostScheduler HLELowcostPeripherialLogMsg:(unsigned char *)data.bytes];
        [model.peripheral writeValue:data forCharacteristic:model.writeCharacteristics type:CBCharacteristicWriteWithoutResponse];
    }else{
        discovermodel = [[self.discoverPeripherals qmui_filterWithBlock:^BOOL(HLELowcostBleInforModel *item) {
            return [item.serialNum isEqualToString:serialNum];
        }] objectOrNilAtIndex:0];
        if (discovermodel && discovermodel.peripheral.state == CBPeripheralStateDisconnected) {
            self.baby.having(discovermodel.peripheral).and.connectToPeripherals().channel(@"111").begin();
        }
    }

    [self.baby setBlockOnConnectedAtChannel:@"111" block:^(CBCentralManager *central, CBPeripheral *peripheral) {
        @strongify(self);
        [self addPeripheral:discovermodel];
        [RACScheduler.mainThreadScheduler afterDelay:0.2 schedule:^{
            [discovermodel.peripheral writeValue:data forCharacteristic:discovermodel.writeCharacteristics type:CBCharacteristicWriteWithoutResponse];
            [HLELowcostScheduler HLELowcostPeripherialLogMsg:(unsigned char *)data.bytes];
        }];
    }];
}
#endif
@end
